package com.ysu.his.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ysu.his.admin.mapper.*;
import com.ysu.his.admin.service.UserService;
import com.ysu.his.constant.RedisConstant;
import com.ysu.his.dto.UserDto;
import com.ysu.his.entity.user.Role;
import com.ysu.his.entity.user.User;
import com.ysu.his.exception.HISException;
import com.ysu.his.vo.UserVo;
import com.ysu.his.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService
{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private DepartmentUserMapper departmentUserMapper;

    @Autowired
    private RegisterLevelMapper registerLevelMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public PageInfo<UserVo> getUserByPage(Integer page, Integer limit, UserDto userDto)
    {
        //启动pageHelper
        PageHelper.startPage(page, limit);

        //查询所有符合条件的用户

        List<User> userList = userMapper.findUserByPage(userDto);
        PageInfo<User> pageInfo = new PageInfo<>(userList);

        List<UserVo> userVoList = new ArrayList<>();
        userList.forEach(user ->
        {
            //查询用户对应的角色
            UserVo userVo = new UserVo();
            BeanUtil.copyProperties(user, userVo);

            String roleJsonStr = (String) redisTemplate.opsForHash()
                    .get(RedisConstant.ALL_ROLE, String.valueOf(user.getRoleId()));

            Role role = JSONUtil.toBean(roleJsonStr,Role.class);
            if (role == null)
            {
                role = roleMapper.selectRoleById(user.getRoleId());
            }

            userVo.setRoleName(role.getRoleName());
            userVoList.add(userVo);
        });

        PageInfo<UserVo> pageInfoVo=new PageInfo<>();
        BeanUtil.copyProperties(pageInfo,pageInfoVo);
        pageInfoVo.setList(userVoList);

        return pageInfoVo;
    }

    @Override
    public void addUser(User user)
    {
        User userDB = userMapper.findUserByWorkNumber(user.getWorkNumber());

        if (userDB!=null)
        {
            throw new HISException(ResultCodeEnum.USER_EXIST);
        }

        //初始化密码
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        user.setPassword(password);
        //初始化用户状态
        user.setStatus(0);

        userMapper.insertUser(user);
    }

    @Override
    public void updateUserInfo(User user)
    {
        userMapper.updateUser(user);
    }

    @Override
    public User getUserInfoById(Long id)
    {
        return userMapper.getUserInfoById(id);
    }

    @Override
    public void startOrStop(Long userId, Integer status)
    {
        userMapper.startOrStop(userId,status);
    }

    @Override
    public void deleteUserById(Long userId)
    {
        userMapper.deleteById(userId);
    }

    @Override
    public List<User> getAllAvailableDoctor()
    {
        List<User> allDoctor = userMapper.findAllDoctor();

        List<User> availableDoctor = new ArrayList<>();
        allDoctor.forEach(doctor->{
            Boolean available = departmentUserMapper.doctorIsAvailable(doctor.getId());
            if (available)
            {
                availableDoctor.add(doctor);
            }
        });

        return availableDoctor;
    }

    @Override
    public List<User> getAllAvailableDoctorScheduling()
    {
        List<User> allDoctor = userMapper.findAllDoctor();

        List<User> availableDoctor = new ArrayList<>();
        allDoctor.forEach(doctor->{
            List<Long> available = registerLevelMapper.doctorIsAvailable(doctor.getId());
            if (CollectionUtils.isEmpty(available))
            {
                availableDoctor.add(doctor);
            }
        });
        return availableDoctor;
    }

    @Override
    public List<User> getDoctorByDepartmentId(Long departmentId)
    {
        List<User> doctorList = departmentUserMapper.getDoctorByDepartmentId(departmentId);
        return doctorList;
    }
}
